//
//  XOWMLoginViewController.m
//  XOWMSDK
//
//  Created by skyline on 2018/7/25.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "XOWMLoginViewController.h"
#import "XOWMPWDViewController.h"
#import "XOWMLoginView.h"
#import "XOWMAccountCell.h"
#import "XOWMRequest.h"
#import "TCCIAP.h"
@interface XOWMLoginViewController()<YJDLoginViewDelegate, YJDRequestDelegate>
@property (nonatomic, strong) XOWMLoginView *loginView;
@property (nonatomic, strong) XOWMRequest *request;
@property (nonatomic, strong) NSDictionary *accountDict;
@property (nonatomic, strong) NSMutableArray *accountArr;
@end
@implementation XOWMLoginViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
}

- (XOWMLoginView *)loginView
{
    if (!_loginView)
    {
        _loginView = [[XOWMLoginView alloc] init];
        _loginView.delegate = self;
        [self.view addSubview:_loginView];
        _loginView.c_center.equal(self.view);
        _loginView.c_size.equal(self.loginView.bounds.size);
    }
    return _loginView;
}

- (XOWMRequest *)request
{
    if (!_request)
    {
        _request = [[XOWMRequest alloc]init];
        _request.delegate = self;
    }
    return _request;
}

- (NSMutableArray *)accountArr
{
    return [XOWMHelper shareHelp].accountArr;
}

- (void)yjd_autoInput:(int)index
{
    if ([self.accountArr count] > index)
    {
        NSString *jsonString = self.accountArr[index];
        self.loginView.nameTF.text = [[[jsonString yjd_dict] allKeys] firstObject];
        self.loginView.passTF.text = [[[jsonString yjd_dict] allValues] firstObject];
    }
}

#pragma mark - YJDLoginViewDelegate
- (void)yjd_YJDLoginViewWithEvent:(YJDLoginViewEvent)event dict:(NSDictionary *)dict
{
    if (event == YJDLoginViewEventLogin)
    {
        if ([self.loginView.nameTF.text length] < 1)  [CCAlert showMessage:@"请输入账户" hidden:nil];
        else if ([self.loginView.passTF.text length] < 1) [CCAlert showMessage:@"请输入密码" hidden:nil];
        else if (![self.loginView.nameTF.text yjd_isNumberOralphabet]) [CCAlert showMessage:@"账户仅限数字或大小写字母" hidden:nil];
        else
        {
            [CCHud startHud];
            self.accountDict = dict;
            [self.request yjd_loginRequest:dict];
        }
        return;
    }
    else if (event == YJDLoginViewEventRegister)
    {
        [self presentViewController:[NSClassFromString(@"XOWMRegisterViewController") new] animated:YES completion:nil];
    }
    else if (event == YJDLoginViewEventForgetPWD)
    {
//        if (VERSION_2_0_0_LATER)
//        {
            XOWMPWDViewController *pwd = [[XOWMPWDViewController alloc] init];
            pwd.type = YJDPWDViewTypeFindPWD;
            [self presentViewController:pwd animated:YES completion:nil];
            return;
//        }
//        else
//            [CCAlert showMessage:@"此功能暂未开放" title:@"提示" enter:nil];
    }
    else if(event == YJDLoginViewEventCancel)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger row = (NSInteger)[self.accountArr count];
    tableView.c_height.equal(20 * ((row > 3)?3:row));
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identenfier = [NSString stringWithFormat:@"XOWMAccountCell%ld",(long)indexPath.row];
    XOWMAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:identenfier];
    if (!cell)
    {
        cell = [[XOWMAccountCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identenfier];
    }
    cell.account = [[[self.accountArr[indexPath.row] yjd_dict] allKeys] firstObject];
    __weak typeof (&*tableView)weakTableView = tableView ;
    NSString *message = [[NSString stringWithFormat:@"删除账号:%@",cell.account] copy];
    cell.block = ^(NSIndexPath *indexPath) {
        [CCAlert showMessage:@"删除账号本地记录，是否继续?" title:message enter:^{
            [self.accountArr removeObjectAtIndex:indexPath.row];
            [weakTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
            [weakTableView endUpdates];
            [self yjd_autoInput:0];
            
            if (self.accountArr.count < 3 )
            {
                weakTableView.c_height.equal(60 - (3 - self.accountArr.count) * 20);
            }
        }];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self yjd_autoInput:(int)indexPath.row];
    tableView.hidden = self.loginView.nameTF.rightBtn.selected;
    self.loginView.nameTF.rightBtn.selected = !self.loginView.nameTF.rightBtn.selected;
    self.loginView.nameTF.rightBtn.customIMG.imageName = (self.loginView.nameTF.rightBtn.selected)?@"up":@"down";
}

#pragma mark - YJDRequestDelegate
- (void)yjd_didRequestWithReceiveData:(NSDictionary *)dict
{
    //关闭菊花
    [CCHud stopHud];
    
    if (!dict)
        return;
    
    int code = [[dict valueForKey:@"code"] intValue];
    NSString *info = [dict valueForKey:@"info"];
    NSString *bindstate = [dict valueForKey:@"bindstate"];
    NSString *phone = [dict valueForKey:@"phone"];
    //成功
    if (code == 100)
    {
        //1.缓存账号密码
        [XOWMHelper yjd_insertAccount:self.accountDict] ;
        [XOWMHelper yjd_setupBindState:phone];
        [XOWMHelper yjd_setupAuthenticate:bindstate];
        [TCCIAP yjd_checkQueueAndDB];
        //2. 登陆成功，直接退出登陆界面，此处写缓存
   
        [self dismissViewControllerAnimated:YES completion:^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(yjd_didreceiveDictYJDLoginViewController:)])
            {
                [self.delegate yjd_didreceiveDictYJDLoginViewController:dict];//这里返回给游戏第三方账号ID和token
            }
        }];
    }
    //失败
    else
    {
        [CCAlert showMessage:[NSString stringWithFormat:@"%@" ,info] title:@"错误" enter:nil];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([@"yjd_背景_1" yjd_image])
    {
        [self.loginView setValue:@"yjd_背景_1" forKeyPath:@"_imageView.imageName"];
    }
    self.loginView.backBtn.hidden = YES;
    self.loginView.titleIMG.content = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_登录_title":@"账号登录";
    self.loginView.tipsLBL.text = @"应文化部要求，请使用手机号码进行注册";
    self.loginView.cancelBtn.content = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_取消_Btn":@"取消";
    self.loginView.nameTF.placeholder = @"请输入账号";
    self.loginView.passTF.placeholder = @"请输入密码";
    self.loginView.enterBtn.content = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_登录_Btn":@"登录";
    self.loginView.leftBtn.content = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_登录_注册_Btn":@"注册账号";
    self.loginView.rightBtn.content = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_登录_密码_Btn":@"忘记密码";
    self.loginView.rightBtn.hidden = [[XOWMPlatform platform].passwordstate isEqualToString:@"0"]?YES:NO;
    [self yjd_autoInput:0];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}


- (void)sp_getUsersMostLiked {
    NSLog(@"Get Info Failed");
}
@end
